package com.kx.center.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Properties;

public class DBUtil {

	// 定义连接数据库的变量

	private static PreparedStatement ps = null;

	private static ResultSet rs = null;

	private static String driver = "";

	private static String url = "";

	private static String username = "";

	private static String password = "";

	// 定义文件属�?
	private static Properties pp = null;

	private static InputStream is = null;
	private static HashMap<String, Connection> conMap = new HashMap<>();

	// 使用静�?�?只需加载�?��
	static {

		try {
			setConnetion();

		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	public static void setConnetion() throws IOException, ClassNotFoundException, SQLException {
		pp = new Properties();

		is = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");

		pp.load(is);

		driver = pp.getProperty("driver1");
		url = pp.getProperty("url1");
		username = pp.getProperty("username1");
		password = pp.getProperty("password1");
		// 加载驱动
		Class.forName(driver);
		Connection conn1 = DriverManager.getConnection(url, username, password);
		conMap.put("kxs", conn1);

		driver = pp.getProperty("driver2");
		url = pp.getProperty("url2");
		username = pp.getProperty("username2");
		password = pp.getProperty("password2");
		// 加载驱动
		Class.forName(driver);
		Connection conn2 = DriverManager.getConnection(url, username, password);
		conMap.put("odb", conn2);
	}

	// 得到连接
	public static Connection getConnection(String key) {
		try {
			if(conMap.get(key) == null || conMap.get(key).isClosed()){
				setConnetion();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conMap.get(key);
	}

	// 关闭资源
	public static void close(ResultSet rs, PreparedStatement ps, Connection ct) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			rs = null;
		}
		if (ps != null) {
			try {
				ps.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			ps = null;
		}
		if (ct != null) {
			try {
				//ct.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//ct = null;
		}
	}

}
